package com.paul.sys.util;

import com.paul.sys.model.Ptstaff;
import javax.servlet.http.*;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by yingg_000 on 2015/9/11.
 */
public class DestorySessionListener implements HttpSessionListener,HttpSessionAttributeListener {

         public   static Map<HttpSession,String> loginUser=new ConcurrentHashMap<HttpSession,String>();

         public void sessionCreated(HttpSessionEvent se) {


        }
        public void sessionDestroyed(HttpSessionEvent se) {
             loginUser.remove(se.getSession());
        }

        public static HttpSession isLogonUser(String usercode) {
        Set<HttpSession> keys = DestorySessionListener.loginUser.keySet();
        for (HttpSession key : keys) {
            if (DestorySessionListener.loginUser.get(key).equals(usercode)) {
                return key;
            }
        }
             return null;
        }

        @Override
        public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
            if (httpSessionBindingEvent.getName().equals("user")) {
                Ptstaff ptstaff=(Ptstaff)httpSessionBindingEvent.getValue();
                HttpSession session=DestorySessionListener.isLogonUser(ptstaff.getCode());
                if(session!=null){
                    //已有用户登录，需要把前面那个用户注销
                    session.removeAttribute("user");//把用户信息移除
                    session.invalidate();
                }
                loginUser.put(httpSessionBindingEvent.getSession(),ptstaff.getCode());
            }
        }

        @Override
        public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
            if(httpSessionBindingEvent.getName().equals("user")){
                loginUser.remove(httpSessionBindingEvent.getSession());
            }
        }

        @Override
        public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
            if(httpSessionBindingEvent.getName().equals("user")){
                Ptstaff ptstaff=(Ptstaff)httpSessionBindingEvent.getValue();
                loginUser.replace(httpSessionBindingEvent.getSession(),ptstaff.getCode());
            }
        }
}

